﻿using JNPF.Basics.Models;
using JNPF.Utils;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace JNPF.Basics.Logic
{
    /// <summary>
    /// 机构管理
    /// 版 本：V3.0.0
    /// 版 权：引迈信息技术有限公司（https://www.jnpfsoft.com）
    /// 作 者：JNPF开发平台组
    /// 日 期：2017.09.20 
    /// </summary>
    public class OrganizeBll
    {
        private OrganizeIService service = new OrganizeService();
        private PositionBll positionBll = new PositionBll();
        private UserBll userBll = new UserBll();
        private RedisHelper redisHelper = new RedisHelper();
        private List<OrganizeEntity> organizeList = new List<OrganizeEntity>();

        public OrganizeBll()
        {
            if (CacheFactory.Cache.Exists(CacheKey.ORGANIZELIST))
            {
                organizeList = CacheFactory.Cache.Get<List<OrganizeEntity>>(CacheKey.ORGANIZELIST);
            }
            else
            {
                if (UserProvider.Instance.Get() != null)
                {
                    organizeList = service.GetList().Result;
                    CacheFactory.Cache.Insert(CacheKey.ORGANIZELIST, organizeList);
                }
            }
        }

        /// <summary>
        /// 列表
        /// </summary>
        /// <returns></returns>
        public async Task<List<OrganizeEntity>> GetList()
        {
            try
            {
                return await service.GetList();
            }
            catch (Exception ex)
            {
                throw ExceptionEx.Throw(ex);
            }
        }
        /// <summary>
        /// 信息
        /// </summary>
        /// <param name="id">主键值</param>
        /// <returns></returns>
        public async Task<OrganizeEntity> GetInfo(string id)
        {
            try
            {
                return await service.GetInfo(id);
            }
            catch (Exception ex)
            {
                throw ExceptionEx.Throw(ex);
            }
        }
        /// <summary>
        /// 重复验证（名称）
        /// </summary>
        /// <param name="fullName">名称</param>
        /// <param name="id">键值</param>
        /// <returns></returns>
        public async Task<bool> IsExistByFullName(string fullName, string id)
        {
            try
            {
                var condition = ExtLinq.True<OrganizeEntity>().And(m => m.FullName == fullName);
                if (!string.IsNullOrEmpty(id))
                    condition = condition.And(m => m.Id != id);
                return await service.IsExist(condition);
            }
            catch (Exception ex)
            {
                throw ExceptionEx.Throw(ex);
            }
        }
        /// <summary>
        /// 重复验证（编码）
        /// </summary>
        /// <param name="enCode">编码</param>
        /// <param name="id">键值</param>
        /// <returns></returns>
        public async Task<bool> IsExistByEnCode(string enCode, string id)
        {
            try
            {
                var condition = ExtLinq.True<OrganizeEntity>().And(m => m.EnCode == enCode);
                if (!string.IsNullOrEmpty(id))
                    condition = condition.And(m => m.Id != id);
                return await service.IsExist(condition);
            }
            catch (Exception ex)
            {
                throw ExceptionEx.Throw(ex);
            }
        }
        /// <summary>
        /// 判断是否允许删除
        /// </summary>
        /// <param name="id">主键值</param>
        /// <returns></returns>
        public async Task<bool> AllowDelete(string id)
        {
            var subdataCount = (await service.GetList()).FindAll(m => m.ParentId == id).Count;
            var positionCount = (await positionBll.GetList()).FindAll(m => m.OrganizeId == id).Count;
            var userCount = (await userBll.GetList()).FindAll(m => m.OrganizeId == id).Count;
            return (subdataCount + positionCount + userCount == 0);
        }
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="entity">实体对象</param>
        public async Task<int> Delete(OrganizeEntity entity)
        {
            try
            {
                CacheFactory.Cache.Remove(CacheKey.ORGANIZELIST);
                return await service.Delete(entity);
            }
            catch (Exception ex)
            {
                throw ExceptionEx.Throw(ex);
            }
        }
        /// <summary>
        /// 创建
        /// </summary>
        /// <param name="entity">实体对象</param>
        public async Task<int> Create(OrganizeEntity entity)
        {
            try
            {
                CacheFactory.Cache.Remove(CacheKey.ORGANIZELIST);
                entity.Id = CommonHelper.Guid;
                entity.CreatorTime = DateTime.Now;
                entity.LastModifyTime = DateTime.Now;
                entity.CreatorUserId = UserProvider.Instance.Get().UserId;
                return await service.Create(entity);
            }
            catch (Exception ex)
            {
                throw ExceptionEx.Throw(ex);
            }
        }
        /// <summary>
        /// 更新
        /// </summary>
        /// <param name="id">主键值</param>
        /// <param name="entity">实体对象</param>
        public async Task<int> Update(string id, OrganizeEntity entity)
        {
            try
            {
                CacheFactory.Cache.Remove(CacheKey.ORGANIZELIST);
                entity.Id = id;
                entity.LastModifyTime = DateTime.Now;
                entity.LastModifyUserId = UserProvider.Instance.Get().UserId;
                return await service.Update(entity);
            }
            catch (Exception ex)
            {
                throw ExceptionEx.Throw(ex);
            }
        }

        /// <summary>
        /// 根据id获取名字
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public string GetName(string id)
        {
            if (id.IsNullOrEmpty())
            {
                return "";
            }
            var organizeInfo = organizeList.Find(x => x.Id == id);
            if (organizeInfo != null)
            {
                return organizeInfo.FullName;
            }
            else
            {
                return "";
            }
        }

        /// <summary>
        /// 公司名称
        /// </summary>
        /// <param name="OrganizeId"></param>
        /// <returns></returns>
        public async Task<string> GetCompany(string OrganizeId)
        {
            var data = await service.GetInfo(OrganizeId);
            if (data == null || string.IsNullOrEmpty(data.Category))
            {
                return "";
            }
            if (data.Category.Equals("department"))
            {
                return await GetCompany(data.ParentId);
            }
            else
            {
                return data.FullName;
            }
        }

    }
}
